package com.finger.crowd.mvc.config;

import com.finger.crowd.entity.Admin;
import com.finger.crowd.entity.Role;
import com.finger.crowd.service.api.AdminService;
import com.finger.crowd.service.api.AuthService;
import com.finger.crowd.service.api.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Component
public class CrowdUserDetailsService implements UserDetailsService {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private AuthService authService;


    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 根据登录的账号查询Admin
        Admin admin = adminService.getAdminByLoginAcct(username);

        // 获取Id
        Integer id = admin.getId();

        // 根据Id查询全部的角色
        List<Role> roles = roleService.selectAssignedByAdminId(id);

        // 根据Id查询全部的权限
        List<String> authNames = authService.getAuthNameByAdminId(id);

        // 里边存放着 全部的 角色名和权限名
        List<GrantedAuthority> authoritieList = new ArrayList<GrantedAuthority>();

        // 把每一个角色名添加的 authoritieList
        for (Role role : roles) {
            // 注意！！一定要加 ROLE_
            String roleName = "ROLE_" + role.getName();

            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(roleName);

            authoritieList.add(simpleGrantedAuthority);
        }

        // 把每一个权限名添加到 authoritieList
        for (String authName : authNames) {

            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(authName);

            authoritieList.add(simpleGrantedAuthority);
        }

        SecurityAdmin securityAdmin = new SecurityAdmin(admin, authoritieList);

        return securityAdmin;
    }
}
